< previous page page_78 next page >

Page 78
Learning How to Implement the Singleton Pattern in Visual Basic
In C++, you use the Protected keyword to help enforce the Singleton pattern policy. However, in Visual Basic, there is no obvious equivalent. The closest you can come to substituting the Protected keyword is to use the Friend and Static keywords. Class methods and properties declared with the Friend and Static keywords ensure that only classes within the enclosing component have access to these members. Nonetheless, in neither C++ or Visual Basic can you ensure that one and only one instance of a static object will ever be declared. A better idea might be to have your Singleton classes registered and tracked through a centralized Registry class. As Gamma, et al, suggest in Design Patterns, you could create a SingletonRegistry collection class with the following members:
Public Sub register (argObjName As String, argSingleton As Singleton)
'Add to some collection
End Sub
Public Property Get pSingleton()
'Here, you'd set pSingleton to some modular instance variable
End Property
Friend Static Function lookup(ByVal argObjName As String)
'Insert code to actually find the actual Singleton object being sought.
'The ByVal ensures that the name of the object in the argument argObjName
'is not modified. Return some meaningful error code or raise an event if
'object not found.
End Function
You can register the Singleton objects in the Class_Initialize event of each corresponding object's class. Assuming the Singleton class has been named Singleton and the SingletonRegistry class has been instantiated as theSingletonRegistry, the code in the Singleton's Class_Initialize event might look like this:
Private Sub Class_Initialize()
 theSingletonRegistry.register(Singleton, Me)
End Sub
Note
Remember that the
Me keyword refers to the object representing the current instance of the Singleton class. Therefore, if you have a list of Singleton objects, named Singleton1 through Singleton10, and the current instance refers to Singleton7, Me refers to Singleton7.

 
< previous page page_78 next page >

If you like this book, buy it!